import time
from concurrent.futures import ThreadPoolExecutor
from image_download import download_img

# 参考http://c.biancheng.net/view/2627.html

# 使用线程池来执行线程任务的步骤如下：
# 调用 ThreadPoolExecutor 类的构造器创建一个线程池。
# 定义一个普通函数作为线程任务。
# 调用 ThreadPoolExecutor 对象的 submit() 方法来提交线程任务。
# 当不想提交任何任务时，调用 ThreadPoolExecutor 对象的 shutdown() 方法来关闭线程池。

if __name__ == '__main__':
    urls = [
        "https://img-ask.csdnimg.cn/upload/1623844642974.jpg",
        "https://img-ask.csdnimg.cn/upload/1623844642974.jpg",
        "https://img-mid.csdnimg.cn/release/static/image/mid/ask/754909759626128.jpg",
        "https://img-ask.csdn.net/upload/201510/22/1445491909_384819.jpg",
    ]
    pool = ThreadPoolExecutor(max_workers=2)  # 线程池放2个线程
    for url in urls:
        pool.submit(download_img, url) # submit() 方法来提交线程任务
    time.sleep(10)

    pool.shutdown()   # 关闭线程池
     


## 方法二
from concurrent.futures import ThreadPoolExecutor
from image_download import download_img

def test():
    urls = [
        "https://img-ask.csdnimg.cn/upload/1623844642974.jpg",
        "https://img-ask.csdnimg.cn/upload/1623844642974.jpg",
        "https://img-mid.csdnimg.cn/release/static/image/mid/ask/754909759626128.jpg",
        "https://img-ask.csdn.net/upload/201510/22/1445491909_384819.jpg",
    ]
    with ThreadPoolExecutor(max_workers=5) as exe:
        exe.map(download_img,urls)   # map(func, *iterables) 为iterables的每个元素启动一个线程

if __name__ == '__main__':
    test()